<template>
  <div class="stu-course-container">
    <div class="header">
      <h1>我的课程</h1>
    </div>
    
    <div v-loading="loading" class="course-list">
      <template v-if="courses.length > 0">
        <el-row :gutter="20">
          <el-col 
            v-for="course in paginatedCourses" 
            :key="course.courseId"
            :xs="24" :sm="12" :md="8" :lg="6"
          >
            <el-card class="course-card" shadow="hover">
              <div class="card-image">
                <img :src="getCourseImage(course.couPic)" :alt="course.couName">
                <div v-if="course.couPrice > 0" class="price-tag">¥{{ course.couPrice }}</div>
              </div>
              
              <div class="card-content">
                <h3 class="course-title">{{ course.couName }}</h3>
                <p class="course-desc">{{ course.couIntroduction }}</p>
                
                <div class="course-stats">
                  <span class="stat-item">
                    <el-icon><User /></el-icon>
                    {{ course.couCollNum || 0 }}人收藏
                  </span>
                  <span class="stat-item">
                    <el-icon><View /></el-icon>
                    {{ course.clicks || 0 }}次学习
                  </span>
                </div>
                
                <el-button 
                  type="primary" 
                  class="enter-btn"
                  @click="enterCourse(course.courseId)"
                >
                  进入学习
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页控件 -->
        <div class="pagination-container" v-if="courses.length > pageSize">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="courses.length"
            layout="prev, pager, next, jumper"
            background
            @current-change="handlePageChange"
          />
        </div>
      </template>
      
      <template v-else-if="loading">
        <div class="loading-placeholder">
          <el-icon :size="30" color="#409EFC"><Loading /></el-icon>
          <p>课程数据加载中...</p>
        </div>
      </template>
      
      <el-empty v-else description="暂无课程数据" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { User, View, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request'
import defaultCourseImage from '@/assets/fault.png'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const courses = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(8) // 每页8个卡片

// 计算分页后的课程数据
const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return courses.value.slice(start, end)
})

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 获取课程图片
const getCourseImage = (picUrl) => {
  return picUrl || defaultCourseImage
}

// 进入课程
const enterCourse = (courseId) => {
  router.push({
    path: `/learn/${courseId}`,
    query: { from: 'my-courses', timestamp: Date.now() }
  }).catch(err => {
    console.error('跳转错误:', err)
  })
}

// 获取课程数据
const fetchCourses = async () => {
  try {
    loading.value = true
    const userId = authStore.userId

    const response = await fetch(`/api/student/courses/by-user/${userId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const rawData = await response.text()
    const parsedData = JSON.parse(rawData)

    // 处理不同数据结构
    if (Array.isArray(parsedData)) {
      courses.value = parsedData
    } else if (parsedData.data && Array.isArray(parsedData.data)) {
      courses.value = parsedData.data
    } else if (parsedData.list && Array.isArray(parsedData.list)) {
      courses.value = parsedData.list
    } else {
      const possibleArray = Object.values(parsedData).find(v => Array.isArray(v))
      courses.value = possibleArray || []
    }
    
  } catch (error) {
    courses.value = []
    
    if (error.message.includes('401')) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error(error.message || '获取课程失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.stu-course-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 0;
  padding: 20px 0;
}

.course-list {
  min-height: 500px;
}

.loading-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #666;
}

.loading-placeholder p {
  margin-top: 15px;
}

.course-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  cursor: pointer;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.card-image {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%;
  overflow: hidden;
}

.card-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.price-tag {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.card-content {
  padding: 15px;
}

.course-title {
  font-size: 16px;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 15px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #888;
  font-size: 13px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item .el-icon {
  margin-right: 5px;
}

.enter-btn {
  width: 100%;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .header h1 {
    font-size: 20px;
  }
  
  .course-card {
    margin-bottom: 15px;
  }
  
  .pagination-container {
    margin-top: 20px;
  }
  
  .el-pagination button, 
  .el-pagination li:not(.number) {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    margin: 0 2px;
  }
}
</style>